<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button
        type="primary"
        @click="toAdd"
      ><i class="el-icon-plus" />添加分类</el-button>
    </div>
    <el-table
      :data="courseCategoryList"
      style="width: 100%"
      border
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      row-key="id"
    >
      <!-- <el-table-column type="index" label="序号" width="50"> </el-table-column> -->
      <el-table-column prop="categoryName" label="分类名称" width="180" />
      <el-table-column label="缩略图" width="180">
        <template slot-scope="scope">
          <el-button type="text" @click="viewThumbnail(scope.row)">查看缩略图</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="180" :formatter="rendererStatus" />
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="warning" @click="modify(scope.row.id)">修改</el-button>
          <el-button type="danger" @click="remove(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      :title="dialogType == 'Add' ? '增加分类' : '修改分类'"
      :visible.sync="dialogVisible"
      width="800px"
      @close="closeDialog"
    >
      <el-form ref="courseForm" :model="formData" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级分类">
              <treeselect
                v-model="formData.parentId"
                :options="options"
                :normalizer="treeSelectProp"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="分类名称" prop="categoryName">
              <el-input v-model="formData.categoryName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="描述" prop="description">
              <el-input v-model="formData.description" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="缩略图" prop="thumbnail">
              <el-upload
                ref="uploadImage"
                action=""
                :http-request="upload"
                :file-list="fileUrlArr"
                list-type="picture-card"
              >
                <i slot="default" class="el-icon-plus" />
                <div slot="file" slot-scope="{ file }">
                  <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                  <span class="el-upload-list__item-actions">
                    <span
                      class="el-upload-list__item-preview"
                      @click="handlePictureCardPreview(file)"
                    >
                      <i class="el-icon-zoom-in" />
                    </span>
                    <span
                      v-if="!disabled"
                      class="el-upload-list__item-delete"
                      @click="handleDownload(file)"
                    >
                      <i class="el-icon-download" />
                    </span>
                    <span
                      v-if="!disabled"
                      class="el-upload-list__item-delete"
                      @click="handleRemove(file)"
                    >
                      <i class="el-icon-delete" />
                    </span>
                  </span>
                </div>
              </el-upload>
              <el-dialog :visible.sync="uploadDialogVisible" :modal="false">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="查看缩略图" :visible.sync="thumbnailDialogVisible" width="800px">
      <img :src="thumbnailDialogImg" alt="缩略图" width="100%">
    </el-dialog>
  </div>
</template>
<script>
import { categoryList, uploadImg, addCategory, getcategoryById, updateCategory, deleteCategory } from '@/api/course'
import { getRepeatToken } from '@/api/global'
import { deepClone } from '@/utils'
import { Treeselect, LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  name: 'CourseCategory',
  components: {
    Treeselect
  },
  data() {
    return {
      courseCategoryList: [],
      searchEntity: {
        pageNum: 1,
        pageSize: 10,
        entity: {}
      },
      dialogVisible: false,
      formData: {
        thumbnail: '', // 缩略图
        description: '', // 描述
        categoryName: '', // 分类名称
        parentId: '-1', // 上级ID
        createBy: '', // 创建人
        updateBy: '', // 修改人
        id: '', // id
        ext3: '', // 扩展字段3
        ext2: '', // 扩展字段2
        ext1: '', // 扩展字段1
        status: 1 // 状态（1：启用；0：禁用）
      },
      rules: {},
      temp: {},
      dialogType: 'Add',
      options: [],
      dialogImageUrl: '',
      uploadDialogVisible: false,
      disabled: false,
      repeatToken: '',
      thumbnailDialogVisible: false,
      thumbnailDialogImg: '',
      fileUrlArr: []
    }
  },
  created() {
    this.temp = deepClone(this.formData)
    this.initData()
  },
  methods: {
    initData() {
      getRepeatToken().then((res) => {
        this.repeatToken = res.data.token
      })
      categoryList(this.searchEntity).then((res) => {
        this.options = deepClone(res.data.pageInfo.list)
        this.courseCategoryList = res.data.pageInfo.list
      })
    },
    rendererStatus(row, column, cellValue, index) {
      if (cellValue == 1) {
        return '启用'
      } else if (cellValue == 0) {
        return '禁用'
      }
    },
    viewThumbnail(row) {
      this.thumbnailDialogImg = ''
      if (!row.thumbnail) {
        this.$message.warning('当前分类没有缩略图!')
      } else {
        this.thumbnailDialogImg = row.thumbnail
        this.thumbnailDialogVisible = true
      }
    },
    toAdd() {
      this.dialogType = 'Add'
      this.formData = deepClone(this.temp)
      this.dialogVisible = true
    },
    treeSelectProp(node) {
      if (node.id == '-1') {
        return {
          id: node.id,
          label: '顶级分类',
          children: []
        }
      }
      return {
        id: node.id,
        label: node.categoryName,
        children: node.children
      }
    },
    handleRemove(file) {
      this.$refs.uploadImage.handleRemove(file)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.uploadDialogVisible = true
    },
    handleDownload(file) {
      const blob = new Blob([file.url])
      const link = document.createElement('a') // 创建a标签
      link.download = file.name // 防止浏览器识别文件格式,直接打开预览
      link.target = '_blank'
      link.style.display = 'none' // 隐藏a连接
      link.href = URL.createObjectURL(file.raw) // 使用blob创建url
      document.body.appendChild(link) // 添加a标签
      link.click() // 立即触发a标签跳转
      URL.revokeObjectURL(link.href) // 卸载URL.createObjectURL()创建的url
      document.body.removeChild(link) // 移除a标签
    },
    upload(item) {
      const form = new FormData()
      form.append('file', item.file)
      uploadImg(form).then((res) => {
        if (res.meta.code == 200) {
          this.$message.success('上传成功')
          this.formData.thumbnail = res.data.url
        }
      })
    },
    save() {
      this.$refs.courseForm.validate((valid) => {
        if (valid) {
          if (this.dialogType == 'Add') {
            addCategory(this.formData, { token: this.repeatToken })
              .then((res) => {
                if (res.meta.code == 200) {
                  this.$message.success('添加成功!')
                  this.dialogVisible = false
                }
                this.initData()
              })
              .catch(() => {
                this.initData()
              })
          } else {
            updateCategory(this.formData, { token: this.repeatToken }).then(res => {
              if (res.meta.code == 200) {
                this.dialogVisible = false
                this.$message.success('修改成功!')
              }
              this.initData()
            }).catch(err => {
              this.initData()
            })
          }
        } else {
          return false
        }
      })
    },
    modify(id) {
      getcategoryById({ id }).then(res => {
        if (res.meta.code == 200) {
          this.formData = res.data.data
          this.fileUrlArr = [{ name: this.formData.categoryName, url: this.formData.thumbnail }]
          this.dialogType = 'Mod'
          this.dialogVisible = true
        }
      })
    },
    remove(id) {
      this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteCategory(id, { token: this.repeatToken }).then(res => {
          if (res.meta.code === '200') {
            this.initData()
            this.$message.success('操作成功!')
          }
        }).catch(err => {
          this.initData()
        })
      }).catch(() => {})
    },
    closeDialog() {
      this.$refs.uploadImage.clearFiles()
    }
  }
}
</script>
<style scoped>
</style>
